package ltd.util;

import ltd.bean.JacksonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by chinalin on 2017/3/16.
 */
public class JsonUtil {

    private  static  final Logger LOGGER = LoggerFactory.getLogger("JsonUtil.class") ;

//    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() ;

    /**
     * 将 POJO 转为 JSON
     */
    public static <T> String toJson(T obj){
        String json ;
        try {
            json = JacksonMapper.getMapper().writeValueAsString(obj) ;
        } catch (Exception e){
            LOGGER.error("convert POJO to JSON failure", e);
            throw new RuntimeException(e) ;
        }
        return json ;
    }


    /**
     * 将JSON 转为 POJO
     */
    public static <T> T formJson(String json, Class<T> type) {
        T pojo;
        try {
            pojo = JacksonMapper.getMapper().readValue(json, type);
        } catch (Exception e) {
            LOGGER.error("convert JSON to POJO failure", e);
            throw new RuntimeException(e);
        }
        return pojo;
    }

    /**
     * 将JSON 转为 List<POJO>
     */
    public static <T> T formJsontoCollection(String json, Class<T> type) {
        T pojo;
        try {
            pojo = JacksonMapper.getMapper().readValue(json, type);
        } catch (Exception e) {
            LOGGER.error("convert JSON to POJO failure", e);
            throw new RuntimeException(e);
        }
        return pojo;
    }
}
